#!/bin/bash

# Eclipse Mosquitto 2.0.18 GCC本地编译安装脚本
# 用于本地开发和测试

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MOSQUITTO_VERSION="2.0.18"
MOSQUITTO_DIR="mosquitto-${MOSQUITTO_VERSION}"
MOSQUITTO_ARCHIVE="${MOSQUITTO_DIR}.tar.gz"
DOWNLOAD_URL="https://mosquitto.org/files/source/${MOSQUITTO_ARCHIVE}"

# 本地编译配置
TARGET_ARCH="gcc"
BUILD_DIR="${SCRIPT_DIR}/build_${TARGET_ARCH}"
INSTALL_DIR="${SCRIPT_DIR}/install/${TARGET_ARCH}"

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查编译工具
check_toolchain() {
    log_info "检查本地编译工具..."
    
    if ! command -v gcc >/dev/null 2>&1; then
        log_error "未找到GCC编译器"
        exit 1
    fi
    
    if ! command -v make >/dev/null 2>&1; then
        log_error "未找到make工具"
        exit 1
    fi
    
    log_info "编译工具检查通过: $(gcc --version | head -1)"
}

# 下载源码
download_source() {
    log_info "准备Mosquitto源码..."
    
    cd "$SCRIPT_DIR"
    
    if [ -f "$MOSQUITTO_ARCHIVE" ]; then
        log_info "源码包已存在: $MOSQUITTO_ARCHIVE"
    else
        log_info "下载Mosquitto源码包..."
        if command -v wget >/dev/null 2>&1; then
            wget "$DOWNLOAD_URL"
        elif command -v curl >/dev/null 2>&1; then
            curl -L -O "$DOWNLOAD_URL"
        else
            log_error "需要wget或curl来下载源码包"
            log_info "请手动下载: $DOWNLOAD_URL"
            exit 1
        fi
    fi
    
    if [ -d "$MOSQUITTO_DIR" ]; then
        log_info "清理旧的源码目录..."
        rm -rf "$MOSQUITTO_DIR"
    fi
    
    log_info "解压源码包..."
    tar -xzf "$MOSQUITTO_ARCHIVE"
    
    if [ ! -d "$MOSQUITTO_DIR" ]; then
        log_error "解压失败或目录结构不正确"
        exit 1
    fi
    
    log_info "源码准备完成: $MOSQUITTO_DIR"
}

# 编译mosquitto
build_mosquitto() {
    log_info "开始编译Mosquitto for 本地GCC..."
    
    # 创建构建目录
    rm -rf "$BUILD_DIR"
    mkdir -p "$BUILD_DIR"
    mkdir -p "$INSTALL_DIR"
    
    cd "$SCRIPT_DIR/$MOSQUITTO_DIR"
    
    # 创建必要的config.h文件
    cat > config.h << 'EOF'
#ifndef CONFIG_H
#define CONFIG_H

/* Version */
#define VERSION "2.0.18"

/* Threading support */
#define WITH_THREADING 1

/* Static build */
#ifndef WITH_STATIC_LIBRARIES
#define WITH_STATIC_LIBRARIES 1
#endif

/* Disable features we don't need */
#ifndef WITH_TLS
#define WITH_TLS 0
#endif

#ifndef WITH_WEBSOCKETS
#define WITH_WEBSOCKETS 0
#endif

#ifndef WITH_BROKER
#define WITH_BROKER 0
#endif

/* System headers */
#include <sys/time.h>
#include <time.h>
#include <unistd.h>

EOF
    
    # 创建配置文件
    cat > config.mk << EOF
# GCC 本地编译配置
CC=gcc
CXX=g++
AR=ar
STRIP=strip
RANLIB=ranlib

# 安装路径
prefix=${INSTALL_DIR}
exec_prefix=\${prefix}
bindir=\${exec_prefix}/bin
sbindir=\${exec_prefix}/sbin
libdir=\${exec_prefix}/lib
includedir=\${prefix}/include
mandir=\${prefix}/man
sysconfdir=\${prefix}/etc

# 功能配置 - 只编译客户端库
WITH_BROKER=no
WITH_CLIENTS=yes
WITH_LIB=yes
WITH_SHARED_LIBRARIES=yes
WITH_STATIC_LIBRARIES=yes

# 禁用不需要的功能减少依赖
WITH_TLS=no
WITH_TLS_PSK=no
WITH_WEBSOCKETS=no
WITH_DOCS=no
WITH_THREADING=yes

# 编译选项
CFLAGS=-O2 -Wall -fPIC
EOF

    log_info "配置文件创建完成"
    
    # 编译
    log_info "执行make编译..."
    make clean || true
    make -j$(nproc) 2>&1 | tee "${BUILD_DIR}/build.log"
    
    if [ ${PIPESTATUS[0]} -ne 0 ]; then
        log_error "编译失败，查看日志: ${BUILD_DIR}/build.log"
        exit 1
    fi
    
    # 安装
    log_info "安装到目标目录..."
    make install 2>&1 | tee "${BUILD_DIR}/install.log"
    
    if [ ${PIPESTATUS[0]} -ne 0 ]; then
        log_error "安装失败，查看日志: ${BUILD_DIR}/install.log"
        exit 1
    fi
    
    log_info "编译安装完成"
}

# 验证安装
verify_installation() {
    log_info "验证安装结果..."
    
    # 检查关键文件
    local checks=(
        "${INSTALL_DIR}/include/mosquitto.h"
        "${INSTALL_DIR}/lib/libmosquitto.a"
        "${INSTALL_DIR}/lib/libmosquitto.so"
    )
    
    local missing=0
    for file in "${checks[@]}"; do
        if [ -f "$file" ]; then
            log_info "✓ $file"
        else
            log_warn "✗ $file (缺失)"
            missing=$((missing + 1))
        fi
    done
    
    if [ $missing -eq 0 ]; then
        log_info "所有关键文件检查通过"
    else
        log_warn "有 $missing 个文件缺失，但可能仍然可用"
    fi
    
    # 显示库信息
    if [ -f "${INSTALL_DIR}/lib/libmosquitto.a" ]; then
        local size=$(du -h "${INSTALL_DIR}/lib/libmosquitto.a" | cut -f1)
        log_info "静态库大小: $size"
    fi
    
    # 创建pkg-config文件
    mkdir -p "${INSTALL_DIR}/lib/pkgconfig"
    cat > "${INSTALL_DIR}/lib/pkgconfig/libmosquitto.pc" << EOF
prefix=${INSTALL_DIR}
exec_prefix=\${prefix}
libdir=\${exec_prefix}/lib
includedir=\${prefix}/include

Name: libmosquitto
Description: Eclipse Mosquitto MQTT library
Version: ${MOSQUITTO_VERSION}
Libs: -L\${libdir} -lmosquitto
Cflags: -I\${includedir}
EOF
    
    log_info "pkg-config文件已创建"
}

# 清理
cleanup() {
    log_info "清理临时文件..."
    cd "$SCRIPT_DIR"
    rm -rf "$MOSQUITTO_DIR"
    log_info "清理完成"
}

# 主函数
main() {
    log_info "开始构建Mosquitto for 本地GCC"
    log_info "版本: $MOSQUITTO_VERSION"
    log_info "目标架构: $TARGET_ARCH"
    log_info "安装目录: $INSTALL_DIR"
    
    check_toolchain
    download_source
    build_mosquitto
    verify_installation
    cleanup
    
    log_info "构建完成！"
    log_info ""
    log_info "使用方法:"
    log_info "  头文件: ${INSTALL_DIR}/include/mosquitto.h"
    log_info "  静态库: ${INSTALL_DIR}/lib/libmosquitto.a"
    log_info "  动态库: ${INSTALL_DIR}/lib/libmosquitto.so"
    log_info ""
    log_info "编译示例:"
    log_info "  gcc -I${INSTALL_DIR}/include your_code.c -L${INSTALL_DIR}/lib -lmosquitto"
}

# 执行主函数
main "$@"